package wlt.util;

import org.apache.commons.io.IOUtils;
import org.casbin.jcasbin.main.Enforcer;
import org.casbin.jcasbin.model.Model;
import org.casbin.jcasbin.persist.file_adapter.FileAdapter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author wuliting
 * @date 2021/11/5
 * 工具类，协助加载配置文件，创建Enforcer
**/

public class EnforcerUtil {
    /**
     * @param relativeModelFilePath 相对classpath的路径
     * @param relativePolicyFilePath 相对classpath的路径
     * @return
     * 加载配置文件，创建Enforcer
     */
    public static Enforcer createEnforcer(String relativeModelFilePath, String relativePolicyFilePath) {
        String modelContext = "";
        try {
            modelContext = IOUtils.toString(Objects.requireNonNull(EnforcerUtil.class.getResourceAsStream(relativeModelFilePath)), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Model model = new Model();
        model.loadModelFromText(modelContext);
        Enforcer enforcer = new Enforcer(model,new FileAdapter(System.getProperty("user.dir") + "/src/main/resources" + relativePolicyFilePath));
        return enforcer;
    }
}
